package com.ebeitech.auction.view.homepage;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ebeitech.auction.R;
import com.ebeitech.auction.constants.CommonConstants;
import com.ebeitech.auction.domain.dao.ChatMessageDao;
import com.ebeitech.auction.qqim.util.QQIMUtil;
import com.ebeitech.auction.view.PublicUtil;
import com.ebeitech.auction.view.auction.MessageSendService;
import com.ebeitech.auction.view.setting.UserInfoActivity;
import com.ebeitech.library.constant.MessageConstants;
import com.ebeitech.library.constant.SPConstants;
import com.ebeitech.library.util.SPManager;
import com.ebeitech.library.util.ViewUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by alice on 2017/10/30.
 */
public class HomepageActivity extends BaseActivity {

	public static final int TAB_TODAY = 0;
	public static final int TAB_BEGIN = 1;
	public static final int TAB_FINISH = 2;

	@BindView(R.id.view_top)
	LinearLayout viewTop;
	@BindView(R.id.tvTitle)
	TextView mTvTitle;
	@BindView(R.id.ivTitleProgress)
	View mTitleProgressBar;
	@BindView(R.id.btnBack)
	View btnBack;
	@BindView(R.id.viewPager)
	ViewPager mViewPager;

	private Context mContext;
	private int mCurrentIndex;
	private int mLastIndex;

	private Fragment mTodayFragment;
	private Fragment mBeginFragment;
	private Fragment mFinishFragment;
	private List<Fragment> mFragments = new ArrayList<Fragment>();

	private boolean isHomeShowVersionDialog = false;

	@OnClick({R.id.btnRight})
	void onClick(View view) {
		startActivity(new Intent(mContext, UserInfoActivity.class));
	}

	@OnClick({R.id.btnBack})
	void onBtnBackClick(View view) {
		onBackPressed();
	}

	private BroadcastReceiver mReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			if (intent != null) {
				String action = intent.getAction();
				if (MessageConstants.ACTION_CONNECT_STATUS.equals(action)) {
					int connectStatus = intent.getIntExtra(MessageConstants.CONNECT_STATUS, MessageConstants.DISCONNECTED);
					mConnectHandler.sendEmptyMessage(connectStatus);
				}
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ebei_activity_homepage);
		ButterKnife.bind(this);
		initView();
		if (CommonConstants.IS_MESSAGE_OPEN) {
			QQIMUtil.getInstance().doLogin(this, SPManager.getInstance().get(SPConstants.USER_ACCOUNT, ""));
		}
		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(MessageConstants.ACTION_CONNECT_STATUS);
		registerReceiver(mReceiver, intentFilter);

		// 把未上传的消息置为失败
		new Thread(new Runnable() {
			@Override
			public void run() {
				ChatMessageDao.getInstance().setUnsendMessageFail();
			}
		}).start();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		unregisterReceiver(mReceiver);

		Intent messageIntent = new Intent(mContext, MessageSendService.class);
		messageIntent.setAction("MessageSendService");
		mContext.stopService(messageIntent);
	}

	private void initView() {
		isHomeShowVersionDialog = getIntent().getBooleanExtra("isHomeShowVersionDialog",false);
		if (isHomeShowVersionDialog)
			PublicUtil.checkVersion(this);
		mContext = this;
		btnBack.setVisibility(View.INVISIBLE);
		mTodayFragment = new AuctionListFragment();
		((AuctionListFragment) mTodayFragment).setCurrentTab(TAB_TODAY);
		mBeginFragment = new AuctionListFragment();
		((AuctionListFragment) mBeginFragment).setCurrentTab(TAB_BEGIN);
		mFinishFragment = new AuctionListFragment();
		((AuctionListFragment) mFinishFragment).setCurrentTab(TAB_FINISH);
		mFragments.add(mTodayFragment);
		mFragments.add(mBeginFragment);
		mFragments.add(mFinishFragment);

		mViewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
			@Override
			public int getCount() {
				return mFragments.size();
			}

			@Override
			public boolean isViewFromObject(View view, Object object) {
				return super.isViewFromObject(view, object);
			}

			@Override
			public Object instantiateItem(ViewGroup container, int position) {
				return super.instantiateItem(container, position);
			}

			@Override
			public void destroyItem(ViewGroup container, int position, Object object) {
				super.destroyItem(container, position, object);
			}

			@Override
			public Fragment getItem(int position) {
				return mFragments.get(position);
			}
		});
		mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
			@Override
			public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

			}

			@Override
			public void onPageSelected(int position) {
				mCurrentIndex = position;
				updateTopView();
				mLastIndex = mCurrentIndex;
			}

			@Override
			public void onPageScrollStateChanged(int state) {

			}
		});

		initTopView();

		mLastIndex = -1;
		mCurrentIndex = TAB_TODAY;
		mViewPager.setCurrentItem(mCurrentIndex);
		updateTopView();
		mLastIndex = mCurrentIndex;
	}

	private void initTopView() {
		String[] tabs = new String[] {
				getString(R.string.ebei_auction_today),
				getString(R.string.ebei_auction_begin),
				getString(R.string.ebei_auction_finish)
		};

		for (int i = 0; i < tabs.length; i++) {
			View view = LayoutInflater.from(mContext).inflate(R.layout.ebei_view_homepage_top, null);
			final TextView tabText = (TextView) view.findViewById(R.id.tvTitleName);
			final View tabBottom = view.findViewById(R.id.ivBottom);
			final int position = i;
			tabText.setText(tabs[i]);
			view.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					mCurrentIndex = position;
					if (mCurrentIndex != mLastIndex) {
						mViewPager.setCurrentItem(mCurrentIndex);
					}
				}
			});
			viewTop.addView(view, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, 1));
		}
	}

	private void updateTopView() {
		if (mLastIndex > -1) {
			View view = viewTop.getChildAt(mLastIndex);
			TextView tabTextLast = (TextView) view.findViewById(R.id.tvTitleName);
			View tabBottomLast = view.findViewById(R.id.ivBottom);
			tabTextLast.setSelected(false);
			tabBottomLast.setVisibility(View.INVISIBLE);
		}

		View selectView = viewTop.getChildAt(mCurrentIndex);
		TextView tabText = (TextView) selectView.findViewById(R.id.tvTitleName);
		View tabBottom = selectView.findViewById(R.id.ivBottom);
		tabText.setSelected(true);
		tabBottom.setVisibility(View.VISIBLE);
	}

	public void onTabSelected(int tab) {
		// TODO Auto-generated method stub
		FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
		switch (tab) {
			case TAB_TODAY:
				ft.add(R.id.view_content, mTodayFragment);
				break;
			case TAB_BEGIN:
				ft.add(R.id.view_content, mBeginFragment);
				break;
			case TAB_FINISH:
				ft.add(R.id.view_content, mFinishFragment);
				break;
			default:
				break;
		}
		ft.commit();
	}

	public void onTabUnSelected(int tab) {
		// TODO Auto-generated method stub
		FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
		switch (tab) {
			case TAB_TODAY:
				ft.remove(mTodayFragment);
				break;
			case TAB_BEGIN:
				ft.remove(mBeginFragment);
				break;
			case TAB_FINISH:
				ft.remove(mFinishFragment);
				break;
			default:
				break;
		}
		ft.commit();
	}

	private Handler mConnectHandler = new Handler(Looper.getMainLooper()) {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
				case MessageConstants.CONNECTED:
					mTvTitle.setText(getString(R.string.ebei_app_name));
					mTitleProgressBar.setVisibility(View.GONE);
					break;
				case MessageConstants.CONNECTING:
					mTvTitle.setText(getString(R.string.ebei_do_reconnect));
					mTitleProgressBar.setVisibility(View.VISIBLE);
					break;
				case MessageConstants.DISCONNECTED:
					mTvTitle.setText(getString(R.string.ebei_no_connect));
					mTitleProgressBar.setVisibility(View.GONE);
					break;
				default:
					break;
			}
		}
	};

	private static boolean isExiting = false;
	private Timer mExitTimer;
	private TimerTask mExitTask;

	@Override
	public void onBackPressed() {
		if (isExiting == false) {
			if ((mExitTimer != null)) {
				mExitTimer.cancel();
				mExitTimer = null;
				mExitTask = null;
			}
			mExitTimer = new Timer();
			mExitTask = new TimerTask() {
				@Override
				public void run() {
					isExiting = false;
				}
			};
			isExiting = true;
			ViewUtil.toastMsg(mContext, R.string.ebei_exit_confirm);
			mExitTimer.schedule(mExitTask, 2000);
		} else {
			finish();
		}
	}

}
